package com.ccl.iot.device;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.View;

import com.ccl.iot.privates.BitmapBuilder;

/**
 * @author
 * @description 可调灯
 */
public class DimmerControler extends DeviceControler {
	/*
	 * 	Static functions
	 */
	public static boolean RegisterControlerType() {
		return RegisterControlerType(DimmerControler.class);
	}

	/*
	 * 	Non-static functions
	 */
	private IOTDimmer mDevice;

	public DimmerControler(IOTDimmer device) {
		super(device);

		mDevice = device;
	}

	@Override
	public void setDevice(IOTDevice device) {
		super.setDevice(device);

		mDevice = (IOTDimmer) device;
	}

	@Override
	protected boolean onTouchDown(float aX, float aY) {

		onBitmapChange();
		return true;
	}

	@Override
	protected boolean onTouchMove(float aX, float aY) {
		return true;
	}

	@Override
	protected boolean onTouchUp(float aX, float aY) {
		if (mDevice != null && mView != null) {
			Rect rect = new Rect(mView.getLeft(), mView.getTop(), mView.getRight(), mView.getBottom());
			if (rect.contains((int) aX, (int) aY)) {
				mDevice.turn(mDevice.isOn() == false);
			}
		}
		onBitmapChange();

		return true;
	}

	protected boolean onTouchCancel(float aX, float aY) {

		if (mDevice != null && mView != null) {
			Rect rect = new Rect(mView.getLeft(), mView.getTop(), mView.getRight(), mView.getBottom());
			if (rect.contains((int) aX, (int) aY)) {
				mDevice.turn(mDevice.isOn() == false);
			}
		}

		onBitmapChange();

		return true;
	}

	private View mView;

	private Rect padding = new Rect(12, 12, 12, 12);

	public void setView(View view) {
		mView = view;
	}

	@Override
	public Bitmap getBitmap(int aWidth, int aHeight) {
		if (aWidth > 0 && aHeight > 0 && mDevice != null) {
			Bitmap background = Bitmap.createBitmap(aWidth, aHeight, Config.RGB_565);
			Canvas canvas = new Canvas(background);
			Bitmap bitmap = null;
			// Rect tPadding = super.getPadding();
			int width = Math.abs(aWidth - padding.left - padding.right);
			int height = Math.abs(aHeight - padding.top - padding.bottom);
			if (mDevice.getImageCount() == 0) {
				canvas.drawColor(super.getBackColor());
				bitmap = DimmerIconProvider.Build(mDevice, DeviceIconProvider.KICON_STYLE_DEFAULT, width, height, super.getBackColor(), isTouchDown());
			} else {
				bitmap = BitmapBuilder.GetBitmap(mDevice.getImage(), width, height, false);
				int getHighLigthColor = DimmerIconProvider.GetHighLigthColor(mDevice, isTouchDown());
				canvas.drawColor(getHighLigthColor);
			}
			if (bitmap != null) {
				canvas.drawBitmap(bitmap, padding.top, padding.bottom, new Paint());
				// bitmap.recycle();
			}

			canvas.save();
			canvas.restore();

			return background;
		}
		return null;
	}

}
